package study.sort;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];
        System.out.println("排序前：" + Arrays.toString(arr));
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println("排序后：" + Arrays.toString(arr));
    }

    /**
     * 拆分和合并
     * @param arr 待拆分合并的数组
     * @param left 左下标
     * @param right 右下标
     * @param temp 中转数组
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp){
        if (left < right){
            int mid = (left + right) / 2;
            //向左递归
            mergeSort(arr, left, mid, temp);

            //向右递归
            mergeSort(arr, mid + 1, right, temp);

            //合并
            merge(arr, left, mid, right, temp);
        }

    }

    /**
     * 合并的方法
     * @param arr 待合并的数组
     * @param left 左下标
     * @param mid 中间下标
     * @param right 右下标
     * @param temp 中转数组
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp){
        int leftIndex1 = left;
        int leftIndex2 = mid + 1;
        //temp数组的index
        int tIndex = 0;

        //1 把数组两边填充到temp数组
        while (leftIndex1 <= mid && leftIndex2 <= right){
            if (arr[leftIndex1] <= arr[leftIndex2]){
                temp[tIndex] = arr[leftIndex1];
                leftIndex1++;
                tIndex++;
            }else {
                temp[tIndex] = arr[leftIndex2];
                leftIndex2++;
                tIndex++;
            }
        }

        //2 把剩余的元素复制到temp数组
        while (leftIndex1 <= mid){
            temp[tIndex] = arr[leftIndex1];
            tIndex++;
            leftIndex1++;
        }
        while (leftIndex2 <= right){
            temp[tIndex] = arr[leftIndex2];
            tIndex++;
            leftIndex2++;
        }

        //3 将temp数组拷贝到原数组arr
        tIndex = 0;
        int tempLeft = left;
        while (tempLeft <= right){
            arr[tempLeft] = temp[tIndex];
            tempLeft++;
            tIndex++;
        }

    }
}
